package com.atzongmaotan.reggie.controller;

import com.atzongmaotan.reggie.common.R;
import com.atzongmaotan.reggie.entity.User;
import com.atzongmaotan.reggie.service.UserService;
import com.atzongmaotan.reggie.utils.SMSUtils;
import com.atzongmaotan.reggie.utils.ValidateCodeUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.tomcat.util.file.Matcher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.Objects;

/**
 * ClassName:    UserController
 * Package:  com.atzongmaotan.controller
 * Description:
 *
 * @Author: interface
 * @Create: 2024/6/25 - 下午1:56
 * @Version: v1.0
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session) {
        String phone = user.getPhone();
        if(StringUtils.isNotEmpty(phone)){
            //生成随机4位的验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("code:{}",code);
            //调用阿里云的短信服务API发送短信
            SMSUtils.sendMessage("瑞吉外卖","模板名称", phone, code);
            //将生成的验证码存在session中
            session.setAttribute(phone, code);
            return R.success("手机验证码短信发送成功");
        }
        return R.error("短信发送失败");
    }
    @PostMapping("/login")
    public R<User> login(@RequestBody Map loginMap, HttpSession session) {
        log.info("login:{}",loginMap);
        //获取手机号
        String phone = loginMap.get("phone").toString();
        //获取验证码
        String code = loginMap.get("code").toString();
        //从session中获取code
        String codeSession = (String) session.getAttribute(phone);

        if(StringUtils.isNotEmpty(code) && Objects.equals(codeSession,code)){
            //登陆成功,判断手机号是否为新用户,不是新用户直接注册
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<User>();
            queryWrapper.eq(User::getPhone, phone);
            User user = userService.getOne(queryWrapper);
            if(Objects.isNull(user)){
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);
            }
            //用户登陆之后设置
            session.setAttribute("user", user.getId());
            return R.success(user);
        }
        return R.error("登陆失败");
    }

}
